
#include "../include/TcpClient.h"

TcpClient::TcpClient(QObject *parent) : QObject(parent), m_socket(new QTcpSocket(this)) {
    connect(m_socket, &QTcpSocket::connected, this, &TcpClient::onConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
    connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &TcpClient::onError);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
}

TcpClient::~TcpClient() {
    delete m_socket;
}

bool TcpClient::connectToServer(const QString &host, quint16 port) {
    if (m_socket->state() == QTcpSocket::UnconnectedState) {
        m_socket->connectToHost(host, port);
        return m_socket->waitForConnected(3000); // 等待3秒连接成功
    }
    return false;
}

void TcpClient::onConnected() {
    emit connected();
}

void TcpClient::onDisconnected() {
    emit disconnected();
}



void TcpClient::onReadyRead() {
    QByteArray data = m_socket->readAll();
    emit receivedData(data);
}
void TcpClient::onError(QAbstractSocket::SocketError socketError)
{
    emit error(socketError);
}